package com.anjufang.service.system.impl;

import com.anjufang.entity.AdminUserToken;
import com.anjufang.mapper.AdminUserTokenMapper;
import com.anjufang.oauth2.TokenGenerator;
import com.anjufang.service.system.UserTokenService;
import com.anjufang.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service("sysUserToken")
public class UserTokenServiceImpl implements UserTokenService {
	
	@Autowired
	private AdminUserTokenMapper userTokenMapper;
	
	//24小时后过期
	private final static int EXPIRE =  1000 * 3600 * 24;
	private final static int APP_EXPIRE = 1000 * 3600 * 24 * 10;
	
	@Override
	@Transactional
	public Result createToken(long userId, String loginType) {
		
		//生成一个token
		String token = TokenGenerator.generateValue();
		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + (loginType.equals("app") ? APP_EXPIRE : EXPIRE));

		//判断是否生成过token
		AdminUserToken tokenEntity = new AdminUserToken();
		tokenEntity.setUserId(userId);
		tokenEntity	= userTokenMapper.selectOne(tokenEntity);
		if(tokenEntity == null){
			tokenEntity = new AdminUserToken();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			//保存token
			userTokenMapper.insert(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			userTokenMapper.updateById(tokenEntity);
		}
		Result r = Result.ok().put("token", token).put("expire", EXPIRE);
		return r;
	}

}
